<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addRolesVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 添加角色 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRolesVisible"
        width="30%"
        @close="addRolesClosed"
      >
        <el-form
          :model="addRoles"
          :rules="addRolesRules"
          ref="addRolesRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoles.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoles.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addRolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>

      <el-table :data="rolesList" border stripe style="width: 100%">
        <!-- 展开行 -->
        <el-table-column type="expand" width="50">
          <template slot-scope="scope">
            <el-row
              :gutter="20"
              v-for="(item, index1) in scope.row.children"
              :key="item.id"
              :class="['rowBottom', index1 === 0 ? 'rowTop' : '', 'vcenter']"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRoleById(scope.row, item.id)"
                  >{{ item.authName }}<i class="el-icon-caret-right"></i
                ></el-tag>
              </el-col>
              <el-col :span="19">
                <el-row
                  :gutter="20"
                  v-for="(subItem, index2) in item.children"
                  :key="subItem.id"
                  :class="[index2 === 0 ? '' : 'rowTop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRoleById(scope.row, subItem.id)"
                      >{{ subItem.authName }}<i class="el-icon-caret-right"></i
                    ></el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="subItemItem in subItem.children"
                      :key="subItemItem.id"
                      closable
                      @close="removeRoleById(scope.row, subItemItem.id)"
                      >{{ subItemItem.authName
                      }}<i class="el-icon-caret-right"></i
                    ></el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180">
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRolesDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRole(scope.row.id)"
              >删除</el-button
            >
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑角色 -->
      <el-dialog
        title="编辑角色"
        :visible.sync="editRolesVisible"
        width="30%"
        @close="editRolesClosed"
      >
        <el-form
          :model="editRoles"
          :rules="editRolesRules"
          ref="editRolesRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoles.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoles.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editRolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 树形结构 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightsVisible"
        width="30%"
        @close="setRightsClosed"
      >
        <el-tree :data="rightsList" :props="treeProps" ref="tree" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultRights"></el-tree>
        <span slot="footer">
          <el-button @click="setRightsVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addRolesVisible: false,
      editRolesVisible: false,
      setRightsVisible: false,
      addRoles: {
        roleName: '',
        roleDesc: ''
      },
      editRoles: {
        roleName: '',
        roleDesc: ''
      },
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      editRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认勾选权限
      defaultRights: [],
      roleId: ''
    }
  },
  activated() {},
  watch: {},
  created() {
    this.getRolesList()
  },
  mounted() {},
  methods: {
    //   得到所有角色信息
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      console.log(res)
    },
    removeRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${id}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getRolesList()
          console.log(res)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 添加角色
    addRole() {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入角色名称')
        const { data: res } = await this.$http.post('roles', this.addRoles)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.addRolesVisible = false
        this.getRolesList()
        this.$message.success(res.meta.msg)
        console.log(res)
      })
    },
    addRolesClosed() {
      this.$refs.addRolesRef.resetFields()
    },
    // 编辑角色
    showEditRolesDialog(row) {
      this.editRolesVisible = true
      this.editRoles.id = row.id
      this.editRoles.roleName = row.roleName
      this.editRoles.roleDesc = row.roleDesc
    },
    editRole() {
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入角色名称')
        const { data: res } = await this.$http.put(`roles/${this.editRoles.id}`, this.editRoles)
        if (res.meta.status !== 200) return this.$message.error('编辑失败')
        this.editRolesVisible = false
        this.getRolesList()
        this.$message.success('编辑成功')
        console.log(res)
      })
    },
    editRolesClosed() {
      this.$refs.editRolesRef.resetFields()
    },
    // 根据对应id删除权限
    removeRoleById(row, rightId) {
      console.log(row, rightId)
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${row.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          row.children = res.data
          console.log(res)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配权限
    async showSetRightsDialog(row) {
      this.roleId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.getLeafKeys(row, this.defaultRights)
      this.setRightsVisible = true
      console.log(row)
    },
    // 递归寻找每一个角色的三级权限
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(element => {
        this.getLeafKeys(element, arr)
      })
    },
    setRightsClosed() {
      this.defaultRights = []
    },
    async setRights() {
      const checkedKeys = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      const checkedKeysStr = checkedKeys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: checkedKeysStr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setRightsVisible = false
      console.log(res)
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.rowBottom {
  border-bottom: 1px solid #eee;
}
.rowTop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
